/* -----------------------------------------------------
 iCompose
 UploadView.h
 
 Created by Team: THE BEARD on 10/11/09.
 
 Members who contributed to this file:
 1. Ethan Holmes
 2. Woo Jin Chang
 
 List of changes to previous member:
 Version 1:
 Nov 12, 2009 (Woo Jin)
 - implemented Uploading method
 Nov 13, 2009 (Woo Jin)
 - revised Uploading method
 Nov 14, 2009 (Woo Jin)
 - revised Uploading method
 Nov 15, 2009 (Woo Jin)
 - revised Uploading method
 Nov 17, 2009 (Woo Jin)
 - revised Uploading method
 
 Simon Fraser University, 2009.
 ----------------------------------------------------- */


#import "UploadView.h"


@implementation UploadView

@synthesize mainView;
@synthesize staffArray;
@synthesize dataFilePath;
@synthesize dataFilePathDataBase;
@synthesize row;

-(IBAction)back {
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(void) checkAndCreateDataBase
{
//	BOOL success;
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex: 0];
	self.dataFilePathDataBase = [documentsDirectory stringByAppendingPathComponent: kDataBase];
	
	//NSFileManager *fileManager = [NSFileManager defaultManager];
	//[fileManager fileExistsAtPath: dataFilePathDataBase];
	NSLog( dataFilePathDataBase );
//	if (success) return;
	//new one for test
	/*NSString *urlStr = [[NSString alloc] initWithFormat:@"ftp://practiceobjc.zxq.net/uploads"];
	NSURL *website = [NSURL URLWithString:urlStr];
	
	if(!website)
	{
		NSLog(@"%@ is not a valid URL");
		return;
	}
	NSHost *host = [NSHost hostWithName: @"practiceobjc.zxq.net"];
	NSInputStream *istream = [[NSInputStream alloc] initWithUrl: 
	*/
	
	
	//get DataBase from the website
	//NSString *theURL = [[NSString alloc] @"http://practiceobjc.zxq.net/uploads/%@", kDataBase);
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://practiceobjc.zxq.net/uploads/staffDataBase.sql"]
										  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:60.0];
	
	
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if (theConnection != nil)
	{
		NSLog(@"DataBase: connection succeed!");
		NSURLResponse* response;
		NSError* error;
		NSData* receiveData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
		NSFileManager *fileManager = [NSFileManager defaultManager];		
		NSLog(@"%d bytes", [receiveData length]);
		NSLog(@"description : %@", [receiveData description]);

		NSLog(@"hehe");
		if ([fileManager createFileAtPath:dataFilePathDataBase contents:receiveData attributes: nil] == NO || [receiveData length] == 0) {
			NSLog(@"Couldn't create the copy, create a new one");
	
			if (sqlite3_open([[self dataFilePathDataBase] UTF8String], &database) != SQLITE_OK)
			{
				sqlite3_close(database);
				NSAssert(0, @"Failed to open database");
			}
			else
			{
				NSLog(@"a");
				char *errorMsg;
				NSString *createSQL = @"CREATE TABLE STAFF(NAME TEXT);";
				if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
				{
					sqlite3_close(database);
					NSLog(@"a");
					NSAssert(0, @"Failed to create database");
				}
				createSQL = @"CREATE UNIQUE INDEX STAFF_UNIQUE_1 ON STAFF(NAME);";
				if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
				{
					sqlite3_close(database);
					NSAssert(0, @"Failed to create unique");
				}
			}
			sqlite3_close(database);
	NSLog(@"a");
	//	NSLog(@"%@", path);
		
		}
	}
	else 
	{
		NSLog(@"Connection failed!");
	}
}

-(void) changeAndUploadDataBase
{
	//sqlite3 *database;
	//BOOL flag = TRUE;
	
	if(sqlite3_open([dataFilePathDataBase UTF8String], &database) == SQLITE_OK)
	{
		NSLog(@"a");
		char *errorMsg;
		NSString *sqlStatement = [[NSString alloc] initWithFormat: @"INSERT OR IGNORE INTO STAFF(NAME) VALUES ('%@');", mainView.staff.nameOfComposition] ;
		if(sqlite3_exec(database, [sqlStatement UTF8String], NULL, NULL, &errorMsg)!= SQLITE_OK)
		{
			NSLog(@"c");
			sqlite3_close(database);
			NSAssert(0, @"Failed to insert or replace contain in database");
		}
	}
	sqlite3_close(database);
	NSLog(@"b");
}

// when uploading button is clicked, the file will be uploaded to the web database
-(IBAction)Uploading {

	[self checkAndCreateDataBase];
	//create staff as dat file also database file and store it in iphone 
	NSMutableData *data = [NSMutableData data];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex: 0];
	NSString *path = [documentsDirectory stringByAppendingPathComponent: [mainView.staff nameOfComposition]];
	[self setDataFilePath: path];
	[archiver encodeObject:mainView forKey:kDataKey];
	[archiver finishEncoding];
	[data writeToFile: dataFilePath atomically:YES];
	[archiver release];
	
	NSLog(@"3");
	/*
    iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
	Staff *tempStaff;
	tempStaff = [mainDelegate.staffArray objectAtIndex: row];
	*/
	//[self checkAndCreateDataBase];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	if ([fileManager fileExistsAtPath:dataFilePath] == YES) {
				
		NSMutableData *myData;
		myData = [NSData dataWithContentsOfFile: dataFilePath];
		NSString *urlString = @"http://practiceobjc.zxq.net/upload.php";
	
		// setting up the request object 
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		[request setURL:[NSURL URLWithString:urlString]];
		[request setHTTPMethod:@"POST"];
		if (request) {
			NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
			NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
			NSLog(contentType);
			[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
			//creating the body of the post
			NSMutableData *body = [NSMutableData data];
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", mainView.staff.nameOfComposition] dataUsingEncoding:NSUTF8StringEncoding]];
			[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
			[body appendData:[NSData dataWithData:myData]];
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
			//setting the body of the post to the reqeust
			[request setHTTPBody:body];
			//making the connection to the web server
			NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
			NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
			NSLog(returnString);
			[self changeAndUploadDataBase];
			//NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
			//NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
			//NSLog(contentType);
			[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
			
			myData = [NSData dataWithContentsOfFile: dataFilePathDataBase];
			//creating the body of the post
			body = [NSMutableData data];
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
			[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", kDataBase] dataUsingEncoding:NSUTF8StringEncoding]];
			[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
			[body appendData:[NSData dataWithData:myData]];
			[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
			//setting the body of the post to the reqeust
			[request setHTTPBody:body];
			//NSLog(staff.nameOfComposition);
			//making the connection to the web server
			returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"" message: @"Your file has been successfully uploaded!." delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles:nil];
			NSLog(@"Your file has been successfully uploaded!");
			[alert show];
			[alert release];
		}
		else {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"" message: @"Uploading failed!." delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles:nil];
			NSLog(@"Uploading failed!");
			[alert show];
			[alert release];
		}
	}
	else {
		NSLog(@"Data file doesn't exist!");
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"" message: @"Data file doesn't exist!" delegate: nil cancelButtonTitle: @"Ok" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
	
	if ([fileManager removeItemAtPath:dataFilePath error:NULL] == YES)
	{
		NSLog(@"staff file is deleted");
	}
	else
	{
		NSLog(@"staff file is not deleted");
	}
}

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
	// adding objects to the array
   // [self checkAndCreateDataBase];
    [super viewDidLoad];
	
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
    return [mainDelegate.staffArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	NSUInteger pos = [indexPath row];
	iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];

	if ([mainDelegate.staffArray count] != 0) {
		Staff *staff = [[mainDelegate.staffArray objectAtIndex: pos] staff];
		cell.textLabel.text = staff.nameOfComposition;
	}
	
	//cell.text = [[mainDelegate.staffArray objectAtIndex:indexPath.row] nameOfComposition];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
	row = [indexPath row];
	mainView = [mainDelegate.staffArray objectAtIndex:row];
	
	NSLog(@"No. %i row is being selected", row);
	//iComposeAppDelegate *mainDelegate = (iComposeAppDelegate*)[[UIApplication sharedApplication] delegate];
	//MainView *mainView = [[MainView alloc] initWithNibName:@"MainView" bundle:nil];
	//[mainView initStaff: [mainDelegate.staffArray objectAtIndex: row]];
	//NSLog([mainView.staff nameOfComposition]);
	//[ [mainDelegate.staffArray objectAtIndex: row]initStaff];
	//[self presentModalViewController:[mainDelegate.staffArray objectAtIndex: row] animated: YES];
	
	//[mainView release];
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)dealloc {
    [super dealloc];
}


@end
